package Json;

import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
* @author jie
* @version 创建时间：2018年6月13日 下午11:04:11
* 
* 基于策略
* GsonBuilder 类包含 
* setExclusionStrategies(ExclusionStrategy... strategies)方法用于传入不定长参数的策略方法，
* 用于直接[排除]指定字段名或者指定字段类型。
* 
* setExclusionStrategies 方法在序列化和反序列化时都会生效，
* 如果只是想指定其中一种情况下的排除策略或分别指定排除策略，可以改为使用以下两个方法:
* 
* ‍addSerializationExclusionStrategy(ExclusionStrategy strategy);
* addDeserializationExclusionStrategy(ExclusionStrategy strategy);
* 
*/
public class StrategiesTest {
	public static void main(String[] args) {
		Gson gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
			@Override
			public boolean shouldSkipField(FieldAttributes fieldAttributes) {
				// 排除指定字段名
				return fieldAttributes.getName().equals("intField")|fieldAttributes.getName().equals("booleanField");
			}

			@Override
			public boolean shouldSkipClass(Class<?> aClass) {
				// 排除指定字段类型
				return aClass.getName().equals(double.class.getName());
			}
		}).create();

		Strategies strategies = new Strategies("stringField", 111, 11.22);
		System.out.println();
		System.err.println(gson.toJson(strategies));

		String json = "{\"stringField\":\"stringField\",\"intField\":111,\"doubleField\":11.22}";
		System.out.println("gson 转换 string =="+gson.toJson(json));//todo 失败
		strategies = gson.fromJson(json, Strategies.class);
		System.out.println();
		System.out.println(strategies);
	}

}

class Strategies {

	private String stringField;
	private boolean booleanField ;

	private int intField;

	private double doubleField;

	public Strategies(String stringField, int intField, double doubleField) {
		this.stringField = stringField;
		this.intField = intField;
		this.doubleField = doubleField;
	}

	@Override
	public String toString() {
		return "Strategies [stringField=" + stringField + ", booleanField=" + booleanField + ", intField=" + intField
				+ ", doubleField=" + doubleField + "]";
	}

	

}
